#include "head.h"

void rm(int sockfd,transport_protocol_t *msg)
{
    //拼接虚拟路径（msg.curr_path + "/" + msg.buf ）
    char full_path[200];
    if(strcmp(msg->curr_path,"/"))//strcmp 相等的则返回0
    {
         snprintf(full_path,sizeof(full_path),"%s/%s", msg->curr_path, msg->buf);
    }
    else//当前路径为/的情况
    {
        snprintf(full_path,sizeof(full_path),"/%s",msg->buf);
    }
    MYSQL_RES *result;  
    MYSQL_ROW row;  
    //发送给数据库
    // 执行查询  
    char sql_buf[1024] = {0};
    sprintf(sql_buf,"SELECT *  FROM bd_file where url = '%s'and user_id = %s and file_type = 2 and delete_flag = 0",full_path,msg->user_id);
   
    //TODO  printf("%s\n",sql_buf);

    if (mysql_query(&msg->my_sql,sql_buf)){
        fprintf(stderr, "Query failed: %s\n",mysql_error(&msg->my_sql));
         LOG_WRITE(3,"rm的sql语句查询出现错误");
        return;
    }

    result = mysql_store_result(&msg->my_sql);  
    if (!result) {  
        fprintf(stderr, "%s\n", mysql_error(&msg->my_sql));  
        exit(1);  
    }  
  
    row = mysql_fetch_row(result);  
    if (!row) {  // 如果行不存在  
        char buf[60];  
        int ret = snprintf(buf, sizeof(buf), "删除失败");  
        if (ret < 0 || ret >= sizeof(buf)) {  
            fprintf(stderr, "Error writing to buffer\n");  
        }
        LOG_WRITE(1,"rm的删除失败");
        send(sockfd, buf, strlen(buf), 0); 
    } else {  
        //只要文件存在就进行删除  
        char update_sql[1024] = {0};  
        sprintf(update_sql, "UPDATE bd_file SET delete_flag = 1 WHERE url = '%s' AND user_id = %s", full_path, msg->user_id);  
        if (mysql_query(&msg->my_sql, update_sql)) {  
            fprintf(stderr, "Update failed: %s\n", mysql_error(&msg->my_sql));  
            return;  
        }  
  
        char buf[60];  
        int ret = snprintf(buf, sizeof(buf), "%s存在，删除成功", msg->buf);  
        if (ret < 0 || ret >= sizeof(buf)) {  
            fprintf(stderr, "Error writing to buffer\n");  
        }  
        send(sockfd, buf, strlen(buf), 0);  
    }  
}



